﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MShop.Core.DataAccess;
using MShop.Core;
using System.Linq.Expressions;
using MShop.Core.Domain;
using MShop.Web.Components.Paging;
using MShop.Core.Extensions;
using Castle.Core;
using MShop.Web.Components.ModelBinders;
using MShop.Web.Components.ValueProvider;
namespace MShop.Web.Areas.Admin.Controllers
{

    public class ProductController : SecureController
    {
        private readonly IProductDao _ProductDao;
        private readonly IItemCatDao _ItemCatDao;
        private readonly ISupplierDao _SupplierDao;
        private readonly IBrandDao _BrandDao;
        private readonly ICommonDao<ProductProp> _CommonDao;
        private readonly ICommonDao<ProductImg> _CommonDao2;
        private readonly IDictDao _DictDao;
        public ProductController(IProductDao productDao, IItemCatDao itemcatdao, IBrandDao brandDao, 
            ISupplierDao supplierDao, ICommonDao<ProductProp> commonDao,ICommonDao<ProductImg> commonDao2,IDictDao dictDao)
        {
           // System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CurrentCulture;
            _ItemCatDao = itemcatdao;
            _ProductDao = productDao;
            _BrandDao = brandDao;
            _SupplierDao = supplierDao;
            _CommonDao = commonDao;
            _CommonDao2 = commonDao2;
            _DictDao = dictDao;
        }


        public ActionResult SetPoint()
        {
            ViewData["perpoint"] = this.ShopContext.Settings.PerPoint;
            return View();
        }

        [HttpPost]
        public ActionResult SetPoint(FormCollection form)
        {
            _ProductDao.GetAll().ToList().ForEach((x) => {
                x.Points = (int)(x.ShopPrice * this.ShopContext.Settings.PerPoint);
                _ProductDao.SaveChanges();
            });
            ViewData["msg"] = "更新成功";
            return View();
        }

        public ActionResult Index(int? id, int? page, string key, bool? includesub)
        {


            int pageSize = 10;
            int pageIndex = page.HasValue ? page.Value - 1 : 0;

            IQueryable<Product> q = _ProductDao.Find(x => x.IsDelete == false);

            if (id.HasValue)
            {
                if (includesub.HasValue)
                {


                    if (includesub.Value)
                    {
                        HashSet<int> ids = new HashSet<int>();
                        GetIds(id.Value, ref ids);

                        q = from item in q where ids.Contains(item.CId) select item;
                    }

                    else
                    {
                        q = from item in q where item.CId == id.Value select item;
                    }

                }
                else
                {
                    q = from item in q where item.CId == id.Value select item;
                }
            }



            if (!string.IsNullOrWhiteSpace(key))
            {
                q = from item in q where (item.ProductName.Contains(key)) select item;
            }
            int count = q.Count();

            q = q.OrderByDescending(x => x.Id);
            int skipIndex = pageIndex * pageSize;

            q = q.Skip(skipIndex).Take(pageSize);

            PagedList<Product> pagedlist = new PagedList<Product>(q, pageIndex, pageSize, count);
            ViewData["itemcats"] = _ItemCatDao.Build();
            return View(pagedlist);
        }


        public void GetIds(int id, ref HashSet<int> guids)
        {
            var etype = _ItemCatDao.GetById(id);

            if (etype.HasChild)
            {
                foreach (var item in etype.ChildNodes)
                {
                    guids.Add(item.Id);
                    if (item.HasChild)
                    {
                        GetIds(item.Id, ref guids);
                    }
                }

            }
        }

        public ActionResult Create(int? cid)
        {
            ViewData["Region"] = _DictDao.ToSelectListItem(1,null);
            if (cid.HasValue)
            {
                ViewData["itemcats"] = _ItemCatDao.Build();
                ViewData["selectlist"] = _ItemCatDao.BuildSelectList(cid);
                ViewData["suppliers"] = _SupplierDao.GetAll().ConvertListItem<Supplier>("Name", "Id", null, true);
                ViewData["brands"] = _BrandDao.GetAll().ConvertListItem<Brand>("Name", "Id", null, true);
             
                var product = new Product() { CId = cid.Value };
                product.ItemCat = _ItemCatDao.GetById(cid.Value);
                product.PropertyCount = product.ItemCat.ItemCatProp.Count;
                product.Sort = _ProductDao.Find(x => x.CId == cid.Value).Count() + 1;
                return View(product);
            }
            else
            {
                ViewData["itemcats"] = _ItemCatDao.Build();
                ViewData["selectlist"] = _ItemCatDao.BuildSelectList();
                ViewData["suppliers"] = _SupplierDao.GetAll().ConvertListItem<Supplier>("Name", "Id", null, true);
                ViewData["brands"] = _BrandDao.GetAll().ConvertListItem<Brand>("Name", "Id", null, true);
                var product = new Product();
                if (_ItemCatDao.BuildSelectList().Count == 0)
                {
                    RedirectToAction("Create", "ItemCat");
                }
                product.ItemCat = _ItemCatDao.GetById(int.Parse(_ItemCatDao.BuildSelectList()[0].Value));
                product.PropertyCount = product.ItemCat.ItemCatProp.Count;
                cid=int.Parse(_ItemCatDao.BuildSelectList()[0].Value);
                product.Sort = _ProductDao.Find(x => x.CId == cid).Count() + 1;
                return View(product);
            }
        }

        private string RemoveChar(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                str = str.Replace(";", "").Replace(",", "").Replace("{", "").Replace("}", "").Replace("|", "");
            }
            return str;
        }


        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(int cid, [ProductDataBind] Product product)
        {
            ViewData["itemcats"] = _ItemCatDao.Build();
            ViewData["selectlist"] = _ItemCatDao.BuildSelectList(cid);
            ViewData["brands"] = _BrandDao.GetAll().ConvertListItem<Brand>("Name", "Id", product.BrandId, true);
            ViewData["suppliers"] = _SupplierDao.GetAll().ConvertListItem<Supplier>("Name", "Id", product.SupplierId, true);
            ViewData["Region"] = _DictDao.ToSelectListItem(1, product.Region);
            if (ModelState.IsValid)
            {
                 product.CatName = _ItemCatDao.GetById(product.CId).Name;

                 product.IsPublish = true;
                _ProductDao.Save(product);
                _ProductDao.SaveChanges();
                if (product.ProductSkuProp.Count > 0)
                {
                    return RedirectToAction("createstep2", new { id = product.Id });
                }
                return RedirectToAction("CreatePic", new { id = product.Id });
            }
            else
            {
                return View(product);
            }

        }
        public ActionResult CreatePic(int id)
        {
            ViewData["itemcats"] = _ItemCatDao.Build();
            var product = _ProductDao.GetById(id);
            return View(product);
        }

        public ActionResult Edit(int cid, int id, int actiontype)
        {
            var product = _ProductDao.GetById(id);

            ViewData["itemcats"] = _ItemCatDao.Build();
            ViewData["selectlist"] = _ItemCatDao.BuildSelectList(cid);
            ViewData["suppliers"] = _SupplierDao.GetAll().ConvertListItem<Supplier>("Name", "Id", product.SupplierId, true);
            ViewData["brands"] = _BrandDao.GetAll().ConvertListItem<Brand>("Name", "Id", product.BrandId, true);
            ViewData["Regions"] = _DictDao.ToSelectListItem(1, product.Region);
            return View(product);
        }



        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(int cid, int id, Product model)
        {

            var product = _ProductDao.GetById(id);
            List<ProductProp> listProp = new List<ProductProp>();
            List<ProductSkuProp> listSkuProp = new List<ProductSkuProp>();
            ViewData["Regions"] = _DictDao.ToSelectListItem(1, model.Region);
            #region"actiontype=2"
            if (Request.Params["actiontype"] == "2")
            {

              

                for (int i = 0; i < product.ItemCat.ItemCatProp.Count; i++)
                {
                    ItemCatProp prop = product.ItemCat.ItemCatProp.ToList()[i];
                    string propValue = Request.Form[prop.ItemProp.Field];

                    if (prop.ItemProp.IsKeyProp)
                    {
                        if (string.IsNullOrEmpty(propValue))
                        {
                            ModelState.AddModelError(prop.ItemProp.Field, string.Format("关键属性{0}不能为空", prop.ItemProp.Name));
                        }
                        else
                        {
                            if (prop.ItemProp.IsInputProp)
                            {
                                ProductProp productProp = new ProductProp()
                                {
                                    ProductId = product.Id,
                                    ItemCatPropId = prop.Id,
                                    ItemPropId = prop.ItemProp.Id,
                                    PropName = prop.ItemProp.Name,
                                    PropValue = RemoveChar(propValue)
                                };
                                listProp.Add(productProp);
                            }
                            else
                            {
                                string[] values = propValue.Split(',');
                                foreach (string str in values)
                                {
                                    ProductProp productProp = new ProductProp() { ProductId = product.Id, ItemPropId = prop.ItemProp.Id, ItemCatPropId = prop.Id, PropName = prop.ItemProp.Name, PropValue = RemoveChar(str) };
                                    listProp.Add(productProp);
                                }
                            }
                        }
                    }
                    else if (prop.ItemProp.IsSaleProp)
                    {
                        if (string.IsNullOrEmpty(propValue))
                        {
                            ModelState.AddModelError(prop.ItemProp.Field, string.Format("销售属性{0}不能为空", prop.ItemProp.Name));
                        }
                        else
                        {

                            if (prop.ItemProp.IsInputProp)
                            {
                                ProductSkuProp productProp = new ProductSkuProp() { ItemCatPropId = prop.Id, ItemPropId = prop.ItemProp.Id, PropName = prop.ItemProp.Name, PropValue = propValue };
                                listSkuProp.Add(productProp);
                            }
                            else
                            {
                                string[] values = propValue.Split(',');
                                foreach (string str in values)
                                {
                                    ProductSkuProp productProp = new ProductSkuProp() { ItemCatPropId = prop.Id, ItemPropId = prop.ItemProp.Id, PropName = prop.ItemProp.Name, PropValue = str };
                                    listSkuProp.Add(productProp);
                                }
                            }


                        }
                    }
                    else if (prop.ItemProp.IsItemProp)
                    {
                        if (!string.IsNullOrEmpty(propValue))
                        {
                            if (prop.ItemProp.IsInputProp)
                            {
                                ProductProp productProp = new ProductProp() { ProductId = product.Id, ItemPropId = prop.ItemProp.Id, ItemCatPropId = prop.Id, PropName = prop.ItemProp.Name, PropValue = propValue };
                                listProp.Add(productProp);
                            }
                            else
                            {
                                string[] values = propValue.Split(',');
                                foreach (string str in values)
                                {
                                    ProductProp productProp = new ProductProp() { ProductId = product.Id, ItemPropId = prop.ItemProp.Id, ItemCatPropId = prop.Id, PropName = prop.ItemProp.Name, PropValue = str };
                                    listProp.Add(productProp);
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            if (ModelState.IsValid)
            {
                if (Request.Params["actiontype"] == "2")
                {
                    _ProductDao.Delete(product.SkuPropImg);
                    _ProductDao.Delete(product.Sku);
                    _ProductDao.Delete(product.ProductProp);
                    _ProductDao.Delete(product.ProductSkuProp);

                    listProp.ForEach(x =>
                    {
                        product.ProductProp.Add(x);
                    });
                    listSkuProp.ForEach(x =>
                    {
                        product.ProductSkuProp.Add(x);
                    });
                }

                UpdateModel<Product>(product, new string[]{"BrandId","ProductName","Price","ShopPrice","Points","CollectNum","Status","IsRecommend",
                 "RecommendDay","IsNew","IsVirtual","Unit","Weight","Title","KeyWords","Description","IsPackage","Package","Specification","ListTime","DeListTime",
                   "Desc","HasInvoice","HasWarranty","Warranty","Region","Sort","CId","SaleNum"
                     }, new ProductValueProvider(this.ControllerContext));
                _ProductDao.SaveChanges();

                if (Request.Params["actiontype"] == "2")
                {
                    if (product.ProductSkuPropNames.Count > 0)
                    {
                        return RedirectToAction("createstep2", new { id = product.Id });
                    }
                }

                return RedirectToAction("Index", new { id = cid });

            }




            ViewData["itemcats"] = _ItemCatDao.Build();
            ViewData["selectlist"] = _ItemCatDao.BuildSelectList(cid);
            ViewData["suppliers"] = _SupplierDao.GetAll().ConvertListItem<Supplier>("Name", "Id", product.SupplierId, true);
            ViewData["brands"] = _BrandDao.GetAll().ConvertListItem<Brand>("Name", "Id", product.BrandId, true);

            return View(product);



        }


        public ActionResult SwfUpload(int id)
        {
            ViewData["SessionId"] = Session.SessionID;
            ViewData["maxlimit"] = 10 - _ProductDao.GetById(id).ProductImg.Count;
            var q = _ProductDao.GetById(id);
            return View(q);
        }

        public ActionResult Delete(int id)
        {
          
            Product product = _ProductDao.GetById(id);
            product.IsDelete = true;
            _ProductDao.Delete(product);
            _ProductDao.SaveChanges();
            return RedirectToAction("Index", new { id = product.CId });
        }

        public ActionResult ProductPic(int id)
        {
            ViewData["itemcats"] = _ItemCatDao.Build();
            Product product = _ProductDao.GetById(id);
            return View(product.ProductImg);            
        }

        public ActionResult BigPic(int picid)
        {
            ProductImg Img = _CommonDao2.GetById(picid);
            return View(Img);
        }

        public ActionResult Set(int picid,int id)
        {
            Product product = _ProductDao.GetById(id); 
            var q = from item in _CommonDao2.GetAll() where item.PId == id select item;
            q.ToList().ForEach(x => {
                if (x.Id == picid)
                {
                    product.PicUrl = x.Url;
                    x.IsDefault = true;
                }
                else
                    x.IsDefault = false;
            });
         
         
            _CommonDao2.SaveChanges();
            return RedirectToAction("ProductPic", new { id = id });          
        }

        public ActionResult DeletePic(int picid,int id)
        {

            ProductImg Img = _CommonDao2.GetById(picid);
            _CommonDao2.Delete(Img);
            _CommonDao2.SaveChanges();
            return RedirectToAction("ProductPic", new { id = id });            
        }


        public ActionResult CreateStep2(int id)
        {
            ViewData["itemcats"] = _ItemCatDao.Build();
            var product = _ProductDao.GetById(id);
            product.IsPublish = false;

            ProductSkuProp[] props = product.ProductSkuProp.ToArray();
            _ItemCatDao.SaveChanges();
            return View(product);
        }



        [HttpPost]
        public ActionResult CreateStep2(int hidCount, int id)
        {
            for (int i = 1; i <= hidCount; i++)
            {
                int quantity = 0;
                decimal price = 0;

                if (int.TryParse(Request.Form["quantity_" + i], out quantity))
                {

                }
                else
                {
                    ModelState.AddModelError("quantity_" + i, "输入的格式不对，请输入整数");
                }

                if (decimal.TryParse(Request.Form["price_" + i], out price))
                {

                }
                else
                {
                    ModelState.AddModelError("price_" + i, "输入的格式不对，请输入整数或者浮点数");
                }
            }
            if (ModelState.IsValid)
            {
                Product product = _ProductDao.GetById(id);
                for (int i = 1; i <= hidCount; i++)
                {
                    int quantity = 0;
                    decimal price = 0;

                    quantity = int.Parse(Request.Form["quantity_" + i]);
                    price = decimal.Parse(Request.Form["price_" + i]);

                    Sku sku = new Sku()
                    {
                        ProductId = product.Id,
                        Created = DateTime.Now,
                        Modified = DateTime.Now,
                        Price = price,
                        Quantity = quantity,
                        Status = 1,
                        SkuId = Request.Form["hid_" + i]
                    };
                    product.Sku.Add(sku);
                }
                product.IsPublish = true;
                var collectNum = product.Sku.Sum(x => x.Quantity);
                product.CollectNum = collectNum;
                _ProductDao.SaveChanges();

                return RedirectToAction("createpic", new { id = product.Id });

                
            }
            else
            {
                ViewData["itemcats"] = _ItemCatDao.Build();
                var product = _ProductDao.GetById(id);
                return View(product);
            }
        }
    }
}
